<template>
  <div class="patrol-category-container">
    <div class="patrol-header">
      <h2>巡更分类</h2>
      <el-select
          v-model="selectedCommunity"
          placeholder="选择小区"
          @change="loadCategories"
          style="width: 200px; margin-right: 10px;"
      >
        <el-option
            v-for="community in communityList"
            :key="community.id"
            :label="community.name"
            :value="community.id"
        ></el-option>
      </el-select>
      <el-button type="primary" @click="addCategory">
        <Plus /> 添加分类
      </el-button>
    </div>

    <el-table
        :data="categories"
        border
        style="width: 100%;"
        v-loading="loading"
    >
      <el-table-column prop="categoryName" label="分类名称" width="150" />
      <el-table-column prop="communityName" label="所属社区" width="150" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
            {{ scope.row.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180" />
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button
              size="small"
              type="primary"
              @click="editCategory(scope.row)"
              style="margin-right: 5px;"
          >
            编辑
          </el-button>
          <el-button size="small" type="danger" @click="deleteCategory(scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增/编辑分类弹窗 -->
    <el-dialog
        title="巡更分类信息"
        :visible.sync="dialogVisible"
        width="400px"
    >
      <el-form
          :model="formData"
          ref="formRef"
          label-width="120px"
          :rules="formRules"
      >
        <el-form-item label="分类名称" prop="categoryName">
          <el-input v-model="formData.categoryName" />
        </el-form-item>
        <el-form-item label="所属社区" prop="communityId">
          <el-select v-model="formData.communityId" placeholder="请选择社区">
            <el-option
                v-for="community in communityList"
                :key="community.id"
                :label="community.name"
                :value="community.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
              v-model="formData.status"
              active-value="1"
              inactive-value="0"
              active-text="启用"
              inactive-text="禁用"
          ></el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveCategory">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import {
  getCategoryByCommunity,
  addCategory,
  updateCategory,
  deleteCategory as deleteCategoryApi
} from '../api/patrolCategory.js'

export default {
  name: 'PatrolCategory',
  components: {
    Plus
  },
  setup() {
    // 社区列表
    const communityList = ref([
      { id: 1, name: '万象城' },
      { id: 2, name: '万达文旅城' },
      { id: 3, name: '碧桂园' }
    ])

    // 响应式数据
    const selectedCommunity = ref(1)
    const categories = ref([])
    const loading = ref(false)
    const dialogVisible = ref(false)
    const isEdit = ref(false)
    const formRef = ref(null)

    // 表单数据
    const formData = reactive({
      categoryId: null,
      categoryName: '',
      communityId: null,
      status: '1'
    })

    // 表单验证规则
    const formRules = reactive({
      categoryName: [
        { required: true, message: '请输入分类名称', trigger: 'blur' }
      ],
      communityId: [
        { required: true, message: '请选择所属社区', trigger: 'change' }
      ]
    })

    // 加载分类数据
    const loadCategories = async () => {
      try {
        loading.value = true
        let {data:data} = await getCategoryByCommunity(selectedCommunity.value)
        console.log(data)
        if (data.code === 0) {
          categories.value = data.data
        } else {
          ElMessage.error(data.message || '加载分类失败')
        }
      } catch (error) {
        ElMessage.error('网络错误，请稍后重试')
        console.error('加载分类失败:', error)
      } finally {
        loading.value = false
      }
    }

    // 添加分类
    const addCategory = () => {
      isEdit.value = false
      formData.categoryId = null
      formData.categoryName = ''
      formData.communityId = selectedCommunity.value
      formData.status = '1'
      dialogVisible.value = true
    }

    // 编辑分类
    const editCategory = (row) => {
      isEdit.value = true
      formData.categoryId = row.categoryId
      formData.categoryName = row.categoryName
      formData.communityId = row.communityId
      formData.status = row.status.toString()
      dialogVisible.value = true
    }

    // 删除分类
    const deleteCategory = async (row) => {
      try {
        await ElMessageBox.confirm(
            `确定要删除分类 "${row.categoryName}" 吗？`,
            '提示',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }
        )

        let {data:data} = await deleteCategoryApi(row.categoryId)
        if (data.code === 200) {
          ElMessage.success('删除成功')
          loadCategories()
        } else {
          ElMessage.error(data.message || '删除失败')
        }
      } catch (error) {
        // 如果是取消操作，不显示错误信息
        if (error !== 'cancel') {
          ElMessage.error('网络错误，请稍后重试')
          console.error('删除失败:', error)
        }
      }
    }

    // 保存分类
    const saveCategory = async () => {
      // 表单验证
      formRef.value.validate((valid) => {
        if (!valid) return false

        const saveMethod = isEdit.value ? updateCategory : addCategory
        const actionName = isEdit.value ? '更新' : '添加'

        saveMethod(formData)
            .then(res => {
              if (res.code === 200) {
                ElMessage.success(`${actionName}成功`)
                dialogVisible.value = false
                loadCategories()
              } else {
                ElMessage.error(res.message || `${actionName}失败`)
              }
            })
            .catch(error)
      })
    }

    // 错误处理函数
    const error = (err) => {
      ElMessage.error('网络错误，请稍后重试')
      console.error('操作失败:', err)
    }

    // 组件挂载时加载数据
    onMounted(() => {
      loadCategories()
    })

    return {
      communityList,
      selectedCommunity,
      categories,
      loading,
      dialogVisible,
      formData,
      formRules,
      formRef,
      loadCategories,
      addCategory,
      editCategory,
      deleteCategory,
      saveCategory
    }
  }
}
</script>

<style scoped>
.patrol-category-container {
  padding: 20px;
}

.patrol-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.patrol-header h2 {
  margin-right: 20px;
}
</style>